package com.cnaaa.xinqiao.vo;

import com.alibaba.fastjson.JSON;
import lombok.Data;

/**
 * 2018/10/19 Create by 郭文梁
 * BasicJsonResult
 * JSON返回接口，同意JSON放回格式为
 * <pre>
 * <code>
 * {
 *     "code":0,    //返回码 0正常，其他异常
 *     "msg":"OK",  //返回消息
 *     "data":{}/[] //返回数据
 * }
 * </code>
 * </pre>
 *
 * @author 郭文梁
 * @date 2018/10/19
 */
@Data
public class BasicJsonResult<T> {
    public static final int OK_CODE = 0;
    public static final String OK_MSG = "OK";
    public static final String ERROR_MSG = "ERROR";

    public static <T> BasicJsonResult<T> ok(String msg, T data) {
        final BasicJsonResult<T> result = new BasicJsonResult<>();
        result.setCode(OK_CODE);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public static <T> BasicJsonResult<T> ok(T data) {
        return ok(OK_MSG, data);
    }

    public static <T> BasicJsonResult<T> ok(String msg) {
        return ok(msg, null);
    }

    public static <T> BasicJsonResult<T> ok() {
        return ok(null);
    }

    public static <T> BasicJsonResult<T> error(int errCode, String msg, T data) {
        BasicJsonResult<T> result = new BasicJsonResult<>();
        result.setCode(errCode);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }

    public static <T> BasicJsonResult<T> error(int errCode, String msg) {
        return error(errCode, msg, null);
    }

    public static <T> BasicJsonResult<T> error(int errCode) {
        return error(errCode, ERROR_MSG);
    }

    private int code;
    private String msg;
    private T data;

    public String asJSON() {
        return JSON.toJSONString(this);
    }
}
